import axios from 'axios'
import { Message, Notification, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/cookies'
import { UserModule } from '@/store/modules/user'
import { ElLoadingComponent } from 'element-ui/types/loading'

let loadingInstance: ElLoadingComponent
let loadingcount: number = 0
let loadingInstanceArr: ElLoadingComponent[] = []

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, 
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    loadingcount += 1
    loadingInstance = Loading.service({ target: 'body', spinner: 'el-icon-loading', customClass: 'app-loading', background: 'rgba(0, 0, 0, 0.1)' })
    loadingInstanceArr.push(loadingInstance)
    if (UserModule.token) {
      config.headers['Authorization'] = UserModule.token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
 
  response => {
    loadingcount -= 1
    if (!loadingcount) {
      // loadingInstance.close()
      loadingInstanceArr.forEach((item: ElLoadingComponent) => {
        item.close()
      })
      loadingInstanceArr = []
    }

    const res = response.data    // 数据库 返回的数据
    if( res.meta.status >= 400) {
      Notification({
        type: 'error',
        title: '错误信息',
        message: res.meta.msg
      })
      return Promise.reject(res.meta) 
    }
    return res.data
  },
  error => {
    loadingcount -= 1
    if (!loadingcount) loadingInstance.close()
    console.log("error::", error)
    Notification({
      type: 'error',
      title: '错误信息',
      message: error.message
    })
    return Promise.reject(error)
  }
)

export default service
